<?php

class CampaignLogoAction extends sfActions
{
    public function execute($request)
    {
        $job_id = $request->getParameter('job_id');
        $job = Doctrine::getTable('Job')->find($job_id);
        $this->forward404Unless($job);
        $campaign = $job->getLastCampaign();
        $this->forward404Unless($campaign);

        $this->has_logo = (bool) $job->getValue('campaign_image');
        $this->error = null;

        if ($request->getMethod() === sfRequest::POST) {
            $this->setLayout(false);

            $files = $request->getFiles();

            if (!array_key_exists('file', $files)) {
                $this->error = 'No file submitted.';
            } else if ($files['file']['error']) {
                if (in_array($files['file']['error'], array(
                    UPLOAD_ERR_INI_SIZE,
                    UPLOAD_ERR_FORM_SIZE,
                )))
                    $this->error = 'The file size is too large.';
                else
                    $this->error = 'An upload error occured.';
            } else {
                $image_data = file_get_contents($files['file']['tmp_name']);
                if ($image_data === false) {
                    $this->error = 'An upload error occured.';
                } else {
                    $image_data = LogoManager::resizeLogo($image_data);
                    if (!$image_data) {
                        $this->error = 'Unknown image format.';
                    } else {
                        $job->setValue('campaign_image', base64_encode($image_data));
                        $job->save();
                    }
                }
                $this->setLayout(false);
                $this->has_logo = true;
            }
            $this->job = $job;
            return sfView::SUCCESS;
        } else {
            // Return an upload form for the dialog iframe
            if ($request->getParameter('mode') === 'form') {
                $this->job = $job;
                $this->setLayout(false);
                return sfView::SUCCESS;
            }

            $logo_data = $job->getValue('campaign_image');
            echo LogoManager::getImage($logo_data);

            return sfView::NONE;
        }
    }
}

?>
